<template>
  <div class="location-container">
    <!-- 弹窗模式 - 只保留弹窗，移除输入框 -->
    <div v-if="mode === 1" class="location-popup">
      <!-- 移除el-input部分 -->
      
      <el-dialog
        title="选择城市"
        :visible.sync="visible"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-cascader
          v-model="selectedOptions"
          :options="cascaderOptions"
          :props="cascaderProps"
          placeholder="请选择城市"
          @change="handleCascaderChange"
          clearable
          style="width: 100%"
        ></el-cascader>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 级联选择器模式（默认） -->
    <el-cascader
      v-else
      v-model="selectedOptions"
      :options="cascaderOptions"
      :props="cascaderProps"
      placeholder="请选择城市"
      @change="handleDirectChange"
      clearable
      style="width: 100%"
    ></el-cascader>
  </div>
</template>

<script>
import {
  getAllProvinces,
  getCitiesByProvinceId,
} from "@/api/recuriter/register";
import { Message } from "element-ui";

export default {
  name: "LocationSelector",
  props: {
    value: {
      type: String,
      default: "",
    },
    city: {
      type: String,
      default: "",
    },
    // mode参数：1=弹窗模式，2=级联选择器模式，默认2
    mode: {
      type: Number,
      default: 2,
      validator: (value) => {
        return [1, 2].includes(value);
      },
    },
    // 控制弹窗显示/隐藏（新增）
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      provinces: [],
      cascaderOptions: [],
      selectedOptions: [], // 级联选择器选中值
      tempValue: "", // 弹窗模式下的临时值
      cascaderProps: {
        value: "id",
        label: "name",
        children: "cities",
        checkStrictly: false,
        expandTrigger: "click",
      },
      optionsLoaded: false,
    };
  },
  watch: {
    value(val) {
      // 同步父组件传入的值到本地
      this.syncSelectedOptions(val);
    },
    city(val) {
      if (this.optionsLoaded) {
        this.syncCityValue(val);
      }
    },
    mode(val) {
      // 切换模式时重新同步选中值
      this.syncSelectedOptions(this.value);
    },
    // 监听visible变化，重置选择状态
    visible(newVal) {
      if (!newVal) {
        this.selectedOptions = [];
        this.tempValue = "";
      }
    }
  },
  async created() {
    await this.loadProvinces();
    this.optionsLoaded = true;

    // 初始化时同步城市值
    if (this.city) {
      this.syncCityValue(this.city);
    }
  },
  methods: {
    // 加载省份数据
    async loadProvinces() {
      try {
        const response = await getAllProvinces();
        if (response?.data?.code === 201) {
          this.provinces = response.data.data;
          await this.formatCascaderOptions();
        } else {
          Message.error("获取省份数据失败");
        }
      } catch (error) {
        console.error("加载省份失败:", error);
        Message.error("获取省份数据失败");
      }
    },

    // 格式化级联选择器选项
    async formatCascaderOptions() {
      this.cascaderOptions = await Promise.all(
        this.provinces.map(async (province) => {
          if (province.municipal) {
            return {
              id: province.id,
              name: province.provinceName,
              isMunicipal: true,
              children: null,
            };
          }

          try {
            const response = await getCitiesByProvinceId(province.id);
            const cities =
              response.data?.code === 201
                ? response.data.data.map((city) => ({
                    id: city.cityName,
                    name: city.cityName,
                  }))
                : [];

            return {
              id: province.id,
              name: province.provinceName,
              isMunicipal: false,
              cities,
            };
          } catch (error) {
            console.error(`加载${province.provinceName}城市失败:`, error);
            return { id: province.id, name: province.provinceName, cities: [] };
          }
        })
      );
    },

    // 弹窗模式：级联选择器值变化（暂存）
    handleCascaderChange(selected) {
      if (!selected || selected.length === 0) {
        this.tempValue = "";
        return;
      }
      const [provinceId, cityName] = selected;
      const province = this.provinces.find((p) => p.id === provinceId);

      if (province?.municipal) {
        this.tempValue = province.provinceName;
      } else if (cityName) {
        this.tempValue = cityName;
      }
    },

    // 弹窗模式：确认选择
    handleConfirm() {
      if (this.tempValue) {
        this.$emit("input", this.tempValue);
        this.$emit("change", this.tempValue);
        this.$emit("confirm", this.tempValue); // 触发确认事件
      }
      this.$emit("update:visible", false); // 通知父组件关闭弹窗
    },

    // 弹窗模式：取消选择
    handleCancel() {
      this.$emit("update:visible", false); // 通知父组件关闭弹窗
      this.$emit("close"); // 触发关闭事件
    },

    handleDirectChange(selected) {
      if (!selected || selected.length === 0) {
        this.$emit("input", "");
        this.$emit("change", "");
        return;
      }
      const [provinceId, cityName] = selected;
      const province = this.provinces.find((p) => p.id === provinceId);

      let result = "";
      if (province?.municipal) {
        result = province.provinceName;
      } else if (cityName) {
        result = cityName;
      }

      this.$emit("input", result);
      this.$emit("change", result);
    },

    // 同步选中值到级联选择器
    syncSelectedOptions(val) {
      if (!val) {
        this.selectedOptions = [];
        this.tempValue = "";
        return;
      }

      for (const province of this.cascaderOptions) {
        if (province.isMunicipal && province.name === val) {
          this.selectedOptions = [province.id];
          this.tempValue = val;
          return;
        }
        const city = province.cities?.find((c) => c.name === val);
        if (city) {
          this.selectedOptions = [province.id, city.id];
          this.tempValue = val;
          return;
        }
      }
    },

    syncCityValue(city) {
      if (!city) {
        this.selectedOptions = [];
        this.tempValue = "";
        return;
      }

      for (const province of this.cascaderOptions) {
        if (province.isMunicipal && province.name === city) {
          this.selectedOptions = [province.id];
          this.tempValue = city;
          return;
        }

        if (province.cities) {
          const cityItem = province.cities.find((c) => c.name === city);
          if (cityItem) {
            this.selectedOptions = [province.id, cityItem.id];
            this.tempValue = city;
            return;
          }
        }
      }
      this.selectedOptions = [];
      this.tempValue = "";
    },
  },
};
</script>

<style scoped>
.location-container {
  width: 100%;
}

.location-popup {
  width: 100%;
}

::v-deep .el-cascader {
  width: 100%;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
